//
//  ZMSelectCityView.swift
//  TravelForUser
//
//  Created by Rowling on 2020/9/23.
//  Copyright © 2020 智蚂优服. All rights reserved.
//

import UIKit
import PGPickerView

class ZMProvinceCityView: XMBaseView {
    
    let disposeBag = DisposeBag()
    
    
    public class func show(_ isArea: Bool = true, _ clickBlock: ((_ province: CommonModels.CityModel, _ city: CommonModels.CityModel, _ area: CommonModels.CityModel?)->())?) {
        let v = ZMUtil.loadNibView(nibName: ZMProvinceCityView.self)
        v.isArea = isArea
        v.frame = SCREEN_BOUNDS
        v.block = clickBlock
//        v.getData()
        APPWindow?.addSubview(v)
    }
    
    func getData() {
        if cityArr.count > 0 {return}
//        let path = Bundle.main.path(forResource: "city", ofType: "json")
//        let url = URL(fileURLWithPath: path!)
//        do {
//            let data = try Data(contentsOf: url)
//            let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
//            let jsonArr = jsonData as! NSArray
//            cityArr = JSONDeserializer<ZMProvinceModel>.deserializeModelArrayFrom(array: jsonArr) as! [ZMProvinceModel]
//            picker.reloadAllComponents()
//        } catch let error as Error? {
//            print("读取本地数据出现错误!",error!)
//        }
        
        CommonService.shared.getCityInfo { info in
            if let info = info {
                self.cityArr = info
                self.picker.reloadAllComponents()
            } else {
                ZMToast.showToast(title: "城市信息加载失败")
                self.removeFromSuperview()
            }
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
//        picker.snp.makeConstraints { (make) in
//            make.width.equalToSuperview()
//        }
        picker.zm.setWidth(SCREEN_W)
        picker.dataSource = self
        picker.delegate = self
        getData()
        ZMUtil.clipCircle(view: bgView, Corner: [.topLeft, .topRight], radius: 4.0)
        picker.reloadAllComponents()
        picker.rx.observe(Array<PGPickerColumnView>.self, "columnViewList").subscribe { (e) in
            if let listArr = e.element as? [PGPickerColumnView]  {
                for listView in listArr {
                    for view in listView.subviews {
                        for table in view.subviews {
                            if let v = table as? PGPickerTableView  {
                                v.bounces = false
                            }
                        }
                    }
                }
            }
        }.disposed(by: disposeBag)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        righeBtn.setTitleColor(Style.mainColor, for: .normal)
    }
                
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var leftBtn: UIButton!
    @IBOutlet weak var righeBtn: UIButton!
    @IBOutlet weak var picker: PGPickerView!{
        didSet {
            picker.rowHeight = 35.0
            picker.lineBackgroundColor = .clear
            picker.textColorOfSelectedRow = UIColor.zm.color333333()
            picker.textFontOfSelectedRow = UIFont.zm.fontSemibold(size: 18)
            picker.textColorOfOtherRow = UIColor.zm.color(hexString: "#B0B0B0")
            picker.textFontOfOtherRow = UIFont.zm.fontRegular(size: 16)
        }
    }
    var block: ((_ province: CommonModels.CityModel, _ city: CommonModels.CityModel, _ area: CommonModels.CityModel?)->())?
    var cityArr = [CommonModels.CityModel]()
    var provinceIndex = 0
    var cityIndex = 0
    var areaIndex = 0
    var isArea = true
}

// MARK: - Button Action
extension ZMProvinceCityView {
    @IBAction func cancelClick(_ sender: UIButton) {
        self.removeFromSuperview()
    }
    
    @IBAction func sureClick(_ sender: UIButton) {
        if let block = block {
            let province = cityArr[provinceIndex]
            var city : CommonModels.CityModel!
            if let child = province.child {
                 city = child[cityIndex]
            } else {
                return
            }
            var area: CommonModels.CityModel?
            if let child = city.child {
                area = child[areaIndex]
            }
            block(province, city, area)
            self.removeFromSuperview()
        }
    }
}


// MARK: - PGPickerViewDataSource, PGPickerViewDelegate
extension ZMProvinceCityView: PGPickerViewDataSource, PGPickerViewDelegate {
    func numberOfComponents(in pickerView: PGPickerView!) -> Int {
        return isArea ? 3 : 2
    }
    
    func pickerView(_ pickerView: PGPickerView!, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return cityArr.count
        } else if component == 1 {
            if let child = cityArr[provinceIndex].child {
                return child.count
            } else {
                return 0
            }
        } else {
            if let child = cityArr[provinceIndex].child, let subChild = child[cityIndex].child {
                return subChild.count
            } else {
                return 0
            }
        }
    }
    
    func pickerView(_ pickerView: PGPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
        if component == 0 {
            return cityArr[row].name
        } else if component == 1 {
            if let child = cityArr[provinceIndex].child {
                return child[row].name
            } else {
                return ""
            }
        } else {
            if let child = cityArr[provinceIndex].child, let subChild = child[cityIndex].child {
                return subChild[row].name
            } else {
                return ""
            }
        }
    }

    func pickerView(_ pickerView: PGPickerView!, didSelectRow row: Int, inComponent component: Int) {
        print(row)
        if component == 0 {
            if row >= cityArr.count {
                pickerView.selectRow(cityArr.count - 1, inComponent: 0, animated: true)
                return
            }
            provinceIndex = row
            cityIndex = 0
            picker.reloadComponent(1)
            picker.reloadComponent(2)
        } else if component == 1 {
            let count = cityArr[provinceIndex].child?.count ?? 0
            if row >= count {
                pickerView.selectRow(count - 1, inComponent: 1, animated: true)
                return
            }
            cityIndex = row
            picker.reloadComponent(2)
        } else {
            let count = cityArr[provinceIndex].child![cityIndex].child?.count ?? 0
            if row >= count {
                pickerView.selectRow(count - 1, inComponent: 2, animated: true)
                return
            }
            areaIndex = row
        }
    }
}
 
class ZMBaseModel: HandyJSON {
    required init() {
    }
}


